package com.example.dense_rack_server.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.dense_rack_server.entity.Archives;
import com.example.dense_rack_server.entity.ArchivesSubname;
import com.example.dense_rack_server.entity.BorrowingRecords;
import com.example.dense_rack_server.entity.Host;
import com.example.dense_rack_server.security.dto.JwtUserDto;
import com.example.dense_rack_server.service.ArchivesService;
import com.example.dense_rack_server.service.ArchivesSubnameService;
import com.example.dense_rack_server.service.BorrowingRecordsService;
import com.example.dense_rack_server.service.HostService;
import com.example.dense_rack_server.utils.DateFormat;
import com.example.dense_rack_server.utils.Netty.SendCmd;
import com.example.dense_rack_server.utils.ResponseModel;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 子档案 前端控制器
 * </p>
 *
 * @author 张彬
 * @since 2025-11-13
 */
@RestController
@RequestMapping("/archives/subname")
public class ArchivesSubnameController {

    @Resource
    public ArchivesSubnameService archivesSubnameService;
    @Resource
    public ArchivesService archivesService;
    @Resource
    public HostService hostService;
    @Resource
    public SendCmd sendCmd;
    @Resource
    public BorrowingRecordsService borrowingRecordsService;

    /**
     * 图纸页面
     */
    @GetMapping("/index")
    public ModelAndView preview(@RequestParam(value = "archivesId") String archivesId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("archivesSubname/table-list");
        modelAndView.addObject("archivesId", archivesId);
        Archives archives = archivesService.getById(archivesId);
        modelAndView.addObject("archivesName", archives.getFileName());
        return modelAndView;
    }


    /**
     * 图纸预览数据
     */
    @ResponseBody
    @GetMapping("/list")
    public Map<String, Object> listTable(@RequestParam(value = "sonFileName", required = false) String sonFileName,
                                         @RequestParam(value = "profile", required = false) String profile,
                                         @RequestParam(value = "archivesId", required = false) String archivesId,
                                         @RequestParam(value = "page") int page,
                                         @RequestParam(value = "limit") int limit) {
        return archivesSubnameService.listTable(sonFileName, profile, archivesId, page, limit);
    }

    /**
     * 图纸新增页面
     */
    @GetMapping("/insert/add")
    public ModelAndView add(@RequestParam(value = "archivesId") String archivesId) {
        ModelAndView modelAndView = new ModelAndView("archivesSubname/add");
        modelAndView.addObject("archivesId", archivesId);
        return modelAndView;
    }

    /**
     * 图纸新增保存
     */
    @PostMapping("/insert/save")
    @ResponseBody
    public ResponseModel insertSave(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("sonFileName"))) {
            return ResponseModel.fail("图纸名称不能为空");
        }
        return archivesSubnameService.insertSave(data);
    }

    /**
     * 图纸预览编辑页面
     */
    @GetMapping("/update/edit/{id}")
    public ModelAndView editView(@PathVariable("id") int id) {
        return archivesSubnameService.editView(id);
    }

    /**
     * 图纸预览编辑页面
     */
    @PostMapping("/update/save")
    @ResponseBody
    public ResponseModel updateSave(@RequestBody JSONObject data) {
        if (StrUtil.isEmpty(data.getStr("sonFileName"))) {
            return ResponseModel.fail("图纸名称不能为空");
        }
        return archivesSubnameService.updateSave(data);
    }

    /**
     * 图纸预览查看
     */
    @GetMapping("/view/{id}")
    public ModelAndView archivesSubnameDetail(@PathVariable("id") int id) {
        return archivesSubnameService.archivesSubnameDetail(id);
    }

    /**
     * 图纸预览删除
     */
    @DeleteMapping("/delete/view/{id}")
    @ResponseBody
    public ResponseModel deleteView(@PathVariable("id") String id) {
        String[] strings = id.split(",");
        boolean deleteSuccess = archivesSubnameService.removeByIds(Arrays.asList(strings));
        return deleteSuccess ? ResponseModel.success("删除成功") : ResponseModel.fail("删除失败");
    }


    /**
     * 图纸页面
     */
    @GetMapping("/borrowing/index")
    public ModelAndView borrowingPreview(@RequestParam(value = "archivesId") String archivesId) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("archivesSubname/borrowingTable");
        modelAndView.addObject("archivesId", archivesId);
        Archives archives = archivesService.getById(archivesId);
        modelAndView.addObject("archivesName", archives.getFileName());
        return modelAndView;
    }

    /**
     * 图纸取出视图
     */
    @GetMapping("/takeout/view")
    public ModelAndView takeoutView(@RequestParam(value = "archivesSubnameId") String archivesSubnameId) {
        return archivesSubnameService.takeoutView(archivesSubnameId);
    }

    /**
     * 图纸取出保存
     */
    @PostMapping("/takeout/save")
    @ResponseBody
    public ResponseModel takeOutSave(@RequestBody JSONObject data) throws InterruptedException {
        ArchivesSubname archivesSubname = archivesSubnameService.getById(data.getInt("id"));

        if (archivesSubname.getDrawingCount() < data.getInt("takeoutCount")) {
            return ResponseModel.fail("图纸数量不足");
        }

        String sysType = archivesService.sysType();
        Archives archives = archivesService.getById(archivesSubname.getArchivesId());

        QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
        hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
        Host host = hostService.getOne(hostQueryWrapper);
        if (!sysType.equals("4")) {
            // 设备状态检查
            if (!archivesService.getDeviceStatus(host)) {
                return ResponseModel.fail("设备未连接，请确认设备开启状态");
            }
            // 下发借阅通知
            String position = null;
            Map<String, Object> borrowingMap = new HashMap<>();
            borrowingMap.put("type", "open_lie_lock");
            position = archivesService.mapCabinetPosition(archives);
            borrowingMap.put("position", position);
            String lockStrMap = JSONUtil.toJsonStr(borrowingMap);
            sendCmd.send(lockStrMap, null, host.getIp());
            // 开灯
            archivesService.openLen(position, host.getIp());
        }
        // 修改档案数量
        archivesSubname.setDrawingCount(archivesSubname.getDrawingCount() - data.getInt("takeoutCount"));
        boolean result = archivesSubnameService.updateById(archivesSubname);
        if (!result) {
            return ResponseModel.fail("档案借阅失败");
        }
        //添加借阅记录
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getUsername();
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileId(archives.getId());
        borrowingRecords.setFileName(archivesSubname.getSonFileName());
        borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
        borrowingRecords.setUserName(userName);
        borrowingRecords.setRemarks(data.getStr("remarks"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        if (sysType.equals("1") || sysType.equals("3")) {
            borrowingRecords.setDataStatus(2);
        } else {
            borrowingRecords.setDataStatus(0);
        }
        borrowingRecords.setStatus(1);
        borrowingRecords.setModuleType(2);
        borrowingRecords.setOperation(userName + "用户借阅" + archives.getFileName() + "档案下" + archivesSubname.getSonFileName() + "图纸"
                + data.getInt("takeoutCount") + "张");
        borrowingRecords.setHostId(host.getId());
        borrowingRecordsService.save(borrowingRecords);
        if (sysType.equals("1") || sysType.equals("3")) {
            return ResponseModel.success("请前往柜体端领取档案");
        } else {
            return ResponseModel.success("档案领取成功");
        }
    }

    /**
     * 图纸归还视图
     */
    @GetMapping("/returning/view")
    public ModelAndView returningView(@RequestParam(value = "archivesSubnameId") String archivesSubnameId) {
        return archivesSubnameService.returningView(archivesSubnameId);
    }

    /**
     * 图纸归还保存
     */
    @PostMapping("/returning/save")
    @ResponseBody
    public ResponseModel returningSave(@RequestBody JSONObject data) throws InterruptedException {
        ArchivesSubname archivesSubname = archivesSubnameService.getById(data.getInt("id"));
        String sysType = archivesService.sysType();
        Archives archives = archivesService.getById(archivesSubname.getArchivesId());


        QueryWrapper<Host> hostQueryWrapper = new QueryWrapper<>();
        hostQueryWrapper.eq("cabinet_number", archives.getAreaCode());
        Host host = hostService.getOne(hostQueryWrapper);
        if (!sysType.equals("4")) {
            // 设备状态检查
            if (!archivesService.getDeviceStatus(host)) {
                return ResponseModel.fail("设备未连接，请确认设备开启状态");
            }
            // 下发归还通知
            String position = null;
            Map<String, Object> restoreMap = new HashMap<>();

            restoreMap.put("type", "open_lie_lock");
            position = archivesService.mapCabinetPosition(archives);

            restoreMap.put("position", position);
            String lockStrMap = JSONUtil.toJsonStr(restoreMap);
            sendCmd.send(lockStrMap, null, host.getIp());
            // 开灯
            archivesService.openLen(position, host.getIp());
        }
        // 修改档案数量
        archivesSubname.setDrawingCount(archivesSubname.getDrawingCount() + data.getInt("returningCount"));
        boolean result = archivesSubnameService.updateById(archivesSubname);
        if (!result) {
            return ResponseModel.fail("档案归还失败");
        }
        //添加借阅记录
        JwtUserDto jwtUserDto = (JwtUserDto) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String userName = jwtUserDto.getUsername();
        BorrowingRecords borrowingRecords = new BorrowingRecords();
        borrowingRecords.setFileId(archives.getId());
        borrowingRecords.setFileName(archivesSubname.getSonFileName());
        borrowingRecords.setDeptId(jwtUserDto.getMyUser().getDeptId());
        borrowingRecords.setUserName(userName);
        borrowingRecords.setRemarks(data.getStr("remarks"));
        borrowingRecords.setCreateTime(DateFormat.getTime());
        if (sysType.equals("1") || sysType.equals("3")) {
            borrowingRecords.setDataStatus(3);
        } else {
            borrowingRecords.setDataStatus(1);
        }
        borrowingRecords.setStatus(1);
        borrowingRecords.setModuleType(2);
        borrowingRecords.setOperation(userName + "用户归还" + archives.getFileName() + "档案下" + archivesSubname.getSonFileName()
                + "图纸" + data.getInt("returningCount") + "张");
        borrowingRecords.setHostId(host.getId());
        borrowingRecordsService.save(borrowingRecords);
        if (sysType.equals("1") || sysType.equals("3")) {
            return ResponseModel.success("请前往柜体端归还档案");
        } else {
            return ResponseModel.success("档案归还成功");
        }
    }
}
